//
//  MusicTools.swift
//  05-播放音乐
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

import UIKit
import AVFoundation

class MusicTools {
    fileprivate static var player : AVAudioPlayer?
}


// MARK:- 对歌曲的控制
extension MusicTools {
    class func playMusic(_ musicName : String) {
        // 1.根据传入的名称获取对应的URL
        guard let url = Bundle.main.url(forResource: musicName, withExtension: nil) else { return }
        
        // 2.判断和之前暂停&停止的音乐是否是同一首歌曲
        if player?.url == url {
            player?.play()
            return
        }
        
        // 3.根据URL,创建AVAudioPlayer对象
        guard let player = try? AVAudioPlayer(contentsOf: url) else { return }
        self.player = player
        
        // 4.播放歌曲
        player.play()
    }
    
    class func pauseMusic() {
        player?.pause()
    }
    
    class func stopMusic() {
        player?.stop()
        player?.currentTime = 0
    }
}


// MARK:- 对其他内容控制(音量/当前时间)
extension MusicTools {
    class func changeVolume(volume : Float) {
        player?.volume = volume
    }
    
    class func setCurrentTime(_ currentTime : TimeInterval) {
        player?.currentTime = currentTime
    }
    
    class func getCurrentTime() -> TimeInterval {
        return player?.currentTime ?? 0
    }
    
    class func getDuration() -> TimeInterval {
        return player?.duration ?? 0
    }
    
    class func setPlayerDelegate(_ delegate : AVAudioPlayerDelegate) {
        player?.delegate = delegate
    }
}
